package com.hnjfzn.message.sms.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.hnjfzn.message.sms.config.AliConfig;
import com.hnjfzn.message.sms.domain.bo.SmsParams;
import com.hnjfzn.message.sms.domain.bo.UtilResult;
import com.hnjfzn.message.sms.service.IThirdService;
import org.springframework.stereotype.Service;

import static com.aliyun.teautil.Common.toJSONString;

@Service
public class ThirdAliServiceImpl implements IThirdService {

    @Override
    public UtilResult send(SmsParams params) {
        UtilResult ur;
        try {
            // 初始化请求客户端
            Client client = new Client(new Config().setAccessKeyId(AliConfig.getAppKey()).setAccessKeySecret(AliConfig.getAppSecret()).setEndpoint(AliConfig.getEndpoint()));
            // 构造请求对象，请填入请求参数值
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(params.getPhone())
                    .setSignName(params.getSign())
                    .setTemplateCode(params.getCode())
                    .setTemplateParam(params.message());

            // 获取响应对象
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

            // 状态
            boolean success = sendSmsResponse.getStatusCode() == 200 && sendSmsResponse.getBody().getCode().equals("OK");

            // 解析
            ur = UtilResult.builder().success(success).msg(sendSmsResponse.getBody().getMessage()).result(toJSONString(sendSmsResponse)).build();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            ur = UtilResult.builder().success(false).msg("获取验证码异常").build();
        }
        return ur;
    }
}
